import { _decorator, animation, CCInteger, Component, EventKeyboard, find, Input, input, KeyCode, Node, UITransform, Vec3 } from 'cc';
import { Joystick } from './Joystick';
const { ccclass, property } = _decorator;

@ccclass('PlayerControl')
export class PlayerControl extends Component {
    // @property({ type: Node })
    // targetNode: Node = null; // 绑定要移动的节点
    // @property
    // moveSpeed: number = 5; // 移动速度
    // private _direction: Vec3 = new Vec3(0, 0, 0);
    // private _isMoving: boolean = false;


    @property(CCInteger)
    private speed: number = 100;
    @property(CCInteger)
    private MapWidth: number = 1280;
    @property(CCInteger)
    private MapHeight: number = 720;

    private stick: Joystick = null;


    private realPlayerWidth: number = 0;
    private realPlayerHeight: number = 0;
    private playerAnchorPointX: number = 0.5;
    private playerAnchorPointY: number = 0.5;

    //当前脚本绑定的Tiledmap地图坐标位置和项目地图大小1/4的偏移量值
    //当前项目为偏移y的值为4,
    // x没有偏移所以不填,如果有偏移要记得同时修改后续代码中地图左右边界的判断逻辑代码
    private offsetMapX: number = 0;
    private offsetMapY: number = 4;


    onLoad() {
        // // 监听键盘按下事件
        // input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);

        // // 监听键盘释放事件
        // input.on(Input.EventType.KEY_UP, this.onKeyUp, this);


        //获取角色的相较父节点Canvas场景的缩放比例


        const scaleX = this.node.scale.x;
        const scaleY = this.node.scale.y;
        //获取角色节点的UITransform中的Size内容尺寸
        const PlayerTransform = this.node.getComponent(UITransform);
        if (PlayerTransform) {
            //获取内容尺寸（Size类型）
            const contentSize = PlayerTransform.contentSize;
            //获取宽度
            var playerWidth = contentSize.width;
            //获取高度
            var playerHeight = contentSize.height;

            //获取角色UITransform的AnchorPoint锚点位置用于后续地图边界计算坐标时x，y要乘上对应的AnchorPoint的值
            //这样进行坐标比对的时候才是和默认(0.5 , 0.5)用实际角色尺寸宽高一半的源代码效果一致
            this.playerAnchorPointX = PlayerTransform.anchorX;
            this.playerAnchorPointY = PlayerTransform.anchorY;
        }
        //根据角色节点的UITransform中的内容尺寸来计算在父节点Canvas中的实际大小。
        this.realPlayerWidth = playerWidth * scaleX;
        this.realPlayerHeight = playerHeight * scaleY;

        const stickNode = find("Canvas/UIRoot/Joystick");
        this.stick = stickNode.getComponent(Joystick);
    }

    onDestroy() {
        // // 移除事件监听
        // input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        // input.off(Input.EventType.KEY_UP, this.onKeyUp, this);


    }

    // onKeyDown(event: EventKeyboard) {
    //     switch (event.keyCode) {
    //         case KeyCode.KEY_W:
    //         case KeyCode.ARROW_UP:
    //             this._direction.y = 1; 
    //             this._isMoving = true;
    //             break;
    //         case KeyCode.KEY_S:
    //         case KeyCode.ARROW_DOWN:
    //             this._direction.y = -1;
    //             this._isMoving = true;
    //             break;
    //         case KeyCode.KEY_A:
    //         case KeyCode.ARROW_LEFT:
    //             this._direction.x = -1;
    //             this._isMoving = true;
    //             break;
    //         case KeyCode.KEY_D:
    //         case KeyCode.ARROW_RIGHT:
    //             this._direction.x = 1;
    //             this._isMoving = true;
    //             break;
    //     }
    // }

    // onKeyUp(event: EventKeyboard) {
    //     switch (event.keyCode) {
    //         case KeyCode.KEY_W:
    //         case KeyCode.ARROW_UP:
    //         case KeyCode.KEY_S:
    //         case KeyCode.ARROW_DOWN:
    //             this._direction.y = 0;
    //             break;
    //         case KeyCode.KEY_A:
    //         case KeyCode.ARROW_LEFT:
    //         case KeyCode.KEY_D:
    //         case KeyCode.ARROW_RIGHT:
    //             this._direction.x = 0;
    //             break;
    //     }
    //     // 当两个方向键都释放时停止移动
    //     if (this._direction.x === 0 && this._direction.y === 0) {
    //         this._isMoving = false;
    //     }
    // }

    update(deltaTime: number) {

        //获取玩家美术子节点的动画控制组件
        let animationController: animation.AnimationController = this.node.getChildByName("character_femaleAdventurer").getComponent(animation.AnimationController);

        //获取玩家目前位置x坐标用于后续判断移动方向控制移动动画
        var oldx = this.node.position.x;

        //设置动画图中变量WalkDir的值重置为0，即角色不移动时处于Idle待机动画。
        animationController.setValue("WalkDir", 0);

        //摇杆偏移量小于0.5时不移动，避免误触
        if (this.stick.dir.length() < 0.5) {
            return;
        }
        var vx = this.speed * this.stick.dir.x;
        var vy = this.speed * this.stick.dir.y;
        var sx = vx * deltaTime;
        var sy = vy * deltaTime;
        var newx = this.node.position.x + sx;
        var newy = this.node.position.y + sy;
        //因为通过Prefab添加角色节点后，角色节点在Battle4地图块的子节点中，不在Canvas节点下了
        //相当于原来在Canvas节点下判断地图的一半即可，但是在Battle4地图块因为是4个图拼一个图，
        //所以对应角色所在节点地图的一半，要在场景大地图的基础上除2后再除2，才是实际判断距离
        //所以下面这两行代码，要改为除4！
        let quarterMapWidth = this.MapWidth / 4;
        let quarterMapHeight = this.MapHeight / 4;

        //实际是乘以AnchorPoint锚点位置的(x,y)对应坐标的比率
        //所以将x,y边界判断都加上了AnchorPoint的参与，使得该代码在不同Size和不同AnchorPoint的玩家节点均能通用
        //同样比较x时，即判断左右边界，也应该乘上对应的比率
        //所以比较地图左边界时要乘以playerAnchorPointX
        let leftPlayerWidth = this.realPlayerWidth * this.playerAnchorPointX;
        //比较地图右边界时要乘以( 1 - playerAnchorPointX )
        let rightPlayerWidth = this.realPlayerWidth * (1 - this.playerAnchorPointX);
        //因为rpg项目中玩家Player1的锚点位置的y修改为了，0.1,那么它基于锚点的上下比例就变成9:1
        //所以比较地图下边界时是乘以0.1，即playerAnchorPointY
        let downPlayerHeight = this.realPlayerHeight * this.playerAnchorPointY;
        //比较上边界时则是乘以（1 - playerAnchorPointY)
        let upPlayerHeight = this.realPlayerHeight * (1 - this.playerAnchorPointY);

        //限定角色移动的地图边界
        if (newx - leftPlayerWidth < quarterMapWidth - this.MapWidth) {         //左边界
            newx = quarterMapWidth - this.MapWidth + leftPlayerWidth;
        } else if (newx + rightPlayerWidth > quarterMapWidth) {    //右边界
            newx = quarterMapWidth - rightPlayerWidth;
        }


        // #由于边界限制由整张地图判断，所以了解问题出在哪以后，后面基于这个偏移量修改整体代码。#

        //因为右下Battle4地图坐标为（320，-184）所以y轴会比整个地图的1/4再向下偏移4坐标
        //所以在Battle4地图下，要把偏移的4坐标加回来，左下Battle3（-320，-184）和Battle4同理
        //同理如果角色Player1节点到左上Battle1（-320,184）会整体向上偏移4坐标，要把偏移的4坐标减回来
        //右上Battle2（320,184）和Battle1同理。
        // const battleMapPos = this.node.position;
        //获取地图坐标位置和项目地图大小1/4的偏移量值
        // if (battleMapPos.y < 0) {
        //     this.offsetMapY = battleMapPos.y + quarterMapHeight;
        // } else if (battleMapPos.y > 0) {
        //     this.offsetMapY = battleMapPos.y - quarterMapHeight;
        // }





        if (newy - downPlayerHeight - this.offsetMapY < -quarterMapHeight) {       //下边界
            newy = -quarterMapHeight + downPlayerHeight + this.offsetMapY;
        } else if (newy + upPlayerHeight - this.offsetMapY > this.MapHeight - quarterMapHeight) {  //上边界
            newy = this.MapHeight - quarterMapHeight - upPlayerHeight + this.offsetMapY;
        }


        //通过判断新x坐标和旧x坐标差值判断移动方向s
        if(newx - oldx > 0){
            animationController.setValue("WalkDir", 1);
        }else if(newx - oldx < 0){
            animationController.setValue("WalkDir", -1);
        }

        // 用于测试运动方向是否正确console.log(animationController.getValue("WalkDir"));
        this.node.setPosition(newx, newy);


    }
}


